﻿using System;
using System.Collections.Generic;
using System.Text.Json;

using Adaptive.Agrona;

using Unity.Type;
using Unity.Type.BinaryType;

namespace Unity.Commons.Client.Offline
{
    public class MemoryJsonHandler : IOfflineHandler
    {
        private readonly List<string> _store;

        private readonly int _size;

        private const int Limit = 100;

        public MemoryJsonHandler() : this(Limit)
        {
        }

        public MemoryJsonHandler(int size)
        {
            if (size < 0)
            {
                throw new ArgumentException("size can't be less zero");
            }

            _size = size > Limit ? Limit : size;
            _store = new List<string>(_size);
        }

        public string[] GetMessages()
        {
            string[] messages = new string[_store.Count];
            _store.CopyTo(0, messages, 0, _store.Count);
            _store.Clear();
            return messages;
        }
        
        private static readonly MetadataEDeserializer Deserializer
            = new MetadataEDeserializer();

        private static readonly JsonSerializerOptions SerializerOptions
            = new JsonSerializerOptions();

        public void onAction(IDirectBuffer buffer, int offset, int length)
        {
            byte[] serializedObject = new byte[length];
            buffer.GetBytes(offset, serializedObject, 0, length);
            MetadataE metadataObject = Deserializer.Deserialize(serializedObject);
            string jsonObject = JsonSerializer.Serialize(metadataObject, SerializerOptions);
            if (_store.Count < Limit)
            {
                _store.Add(jsonObject);
            }
        }
        
    }
}